﻿function createEditPaper(data) {
    initPaper(data).then(function (result) {
        var paper = result.paper;
        if (paper) {
            $("#map").width(result.size.width).height(result.size.height);
            $("#svg").children(":first-child").width("100%").height("100%").css("overflow", "auto");
            var points = [];
            var pencilset = paper.set();
            var toolSet = paper.set();
            var pathy = points;
            var pathnow;
            var penOff = paper.rect(0, 0, 100, 100, 1);
            penOff.attr({ stroke: "hsb(.8, 1, 1)", "stroke-width": 2, opacity: 0.5, "fill": "#068306", "fill-opacity": "0.5" });
            var p1 = paper.path('M25.31,2.872l-3.384-2.127c-0.854-0.536-1.979-0.278-2.517,0.576l-1.334,2.123l6.474,4.066l1.335-2.122C26.42,4.533,26.164,3.407,25.31,2.872z')
                .attr({ 'fill': '#ff00ff', 'stroke-width': '1', 'stroke': 'none', 'fill-opacity': '1', 'stroke-opacity': '1' });
            var p2 = paper.path("M6.555,21.786l6.474,4.066L23.581,9.054l-6.477-4.067L6.555,21.786zM5.566,26.952l-0.143,3.819l3.379-1.787l3.14-1.658l-6.246-3.925L5.566,26.952z")
                .attr({ 'fill': '#ff00ff', 'stroke-width': '1', 'stroke': 'none', 'fill-opacity': '1', 'stroke-opacity': '1' });
            pencilset.push(p1, p2);
            pencilset[0].node.style.cursor = 'pointer';
            pencilset[1].node.style.cursor = 'pointer';
            toolSet.push(penOff);
            toolSet[0].node.style.cursor = 'pointer';
            var start = function () {
                pencilset.oBB = pencilset.getBBox();
            };
            var move = function (dx, dy) {
                var bb = pencilset.getBBox();
                pencilset.translate(pencilset.oBB.x - bb.x + dx, pencilset.oBB.y - bb.y + dy);
            };
            var up = function () {
                pencilset.oBB = pencilset.getBBox();
                var inSet = Raphael.isPointInsideBBox(toolSet.getBBox(), pencilset.oBB.x, pencilset.oBB.y + pencilset.oBB.height);
                if (!inSet) {
                    pathNPoints(pencilset.oBB);
                } else {
                    pathnow = createNewPath(paper, pencilset, data.shapes);
                }
            };
            var pathNPoints = function (bbox) {
                if (!pathnow) {
                    pathnow = createNewPath(paper, pencilset, data.shapes);
                }
                var circle = paper.circle(bbox.x, bbox.y + bbox.height, 5);
                circle.attr({ fill: "hsb(.8, 1, 1)", stroke: "none", opacity: .5 });
                $(circle.node).attr("data-relationPathId", $(pathnow.node).attr("myId"));
                var points2 = $(pathnow.node).data("shape").points;
                points2.push(Math.round(bbox.x), Math.round(bbox.y + bbox.height));
                pathy = "M" + points2.toJSON();
                pathnow.attr({ path: pathy });
                var circles = $(pathnow.node).data("shape").circles;
                circles.push({ x: bbox.x, y: bbox.y + bbox.height });
            };
            pencilset.drag(move, start, up);
            var toolDragStart = function () {
                toolSet.oBB = toolSet.getBBox();
                toolSet.push(p1, p2);
            };
            var toolDragMove = function (dx, dy) {
                var bb = toolSet.getBBox();
                toolSet.translate(toolSet.oBB.x - bb.x + dx, toolSet.oBB.y - bb.y + dy);
            };
            var toolDragEnd = function () {
                toolSet.oBB = toolSet.getBBox();
                toolSet.clear();
                toolSet.push(penOff);
                toolDragEnd2(toolSet.oBB);
            };
            toolSet.drag(toolDragMove, toolDragStart, toolDragEnd);
            $(document).keyup(function (e) {
                if (e.keyCode == 46) {
                    var element = $("#svg").children(":first-child").children("[data-select='select'][data-type='path']");
                    if (element) {
                        var id = $(element).attr("myId");
                        $(element).remove();
                        $("#svg").children(":first-child").children("[data-relationPathId='" + id + "']").remove();
                        $.each(data.shapes, function (index, item) {
                            if (item && item.id == id) {
                                data.shapes.splice(index, 1);
                            }
                        });
                        pathnow = createNewPath(paper, pencilset, data.shapes);
                    }
                    e.preventDefault();
                }
            });
        }
    });
}
function toolDragEnd2(bbox) {
    $("#markerTool").css({ left: bbox.x + 50, top: bbox.y + 35 });
}
function path(paper, id, pathd) {
    var pathy = pathd ? "M" + pathd : [];
    var newPath = paper.path(pathy);
    newPath.attr({ stroke: "hsb(.8, 1, 1)", "stroke-width": 2, opacity: 0.5, fill: "#068306" });
    $(newPath.node)
        .attr("myId", id)
        .attr("data-type", "path")
        .mouseenter(function () { newPath.attr("fill-opacity", "0.5"); })
        .mouseleave(function () { newPath.attr("fill-opacity", "0.9"); })
        .click(function () { setSelectAttr(newPath.node); });
    return newPath;
}
function createNewPath(paper, pencilset, shapes) {
    var id = new Date().getTime();
    var newPath = path(paper, id);
    newPath.insertBefore(pencilset);
    var newPathData = kendo.observable({ points: [], id: id, circles: [], name: "" });
    shapes.push(newPathData);
    $(newPath.node).data("shape", newPathData);
    return newPath;
};
function initTool() {
    $("#markerTool").kendoDraggable({
        hint: function (element) {
            return element.clone();
        }
    });
    $("#map").kendoDropTarget({
        drop: function (e) {
            var hintOffset = e.draggable.hintOffset;
            if ($(e.draggable.hint).data("marker")) {
                var $target = $(e.draggable.currentTarget);
                $target.offset(hintOffset);
                var markerData = $target.data("marker");
                markerData.set("offset", hintOffset);
                markerData.set("position", $target.position());
            } else {
                var markers = $("#marker").data("markers");
                var newMarkerData = kendo.observable({
                    offset: hintOffset,
                    name: "",
                    isEnable: true,
                    isFork: true,
                    isLift: false,
                    accessTo: [],
                    markerId: new Date().getTime(),
                    position: { top: 0, left: 0 }
                });
                marker(newMarkerData);
                markers.push(newMarkerData);
            }

        }
    });
}
function initPaper(data) {
    var dfd = $.Deferred();
    getImgNaturalSize(data.projectImgUrl).then(function (size) {
        var viewBoxWidth = 1000;// size.width;
        var viewBoxHeight = 900;//size.height;
        var paper = Raphael(document.getElementById("svg"), 0, 0, viewBoxWidth, viewBoxHeight);
        if (size) {
            var img = paper.image(data.projectImgUrl, 0, 0, size.width, size.height);
            img.attr("width", size.width);
            img.attr("height", size.height);
        }
        if (data.shapes) {
            data.shapes = new kendo.data.ObservableArray(data.shapes);
            $.map(data.shapes, function (item) {
                if (item.points && item.points.length > 0) {
                    var newPath = path(paper, item.id, item.points.toJSON());
                    $(newPath.node).data("shape", item);
                }
                if (item.circles && item.circles.length > 0) {
                    $.map(item.circles, function (circleData) {
                        var circle = paper.circle(circleData.x, circleData.y, 5);
                        circle.attr({ fill: "hsb(.8, 1, 1)", stroke: "none", opacity: .5 });
                        $(circle.node).attr("data-relationPathId", item.id);
                    });
                }
            });
        } else {
            data.shapes = new kendo.data.ObservableArray([]);
        }
        return dfd.resolve({ paper: paper, size: size });
    });
    return dfd.promise();
}
function getImgNaturalSize(url) {
    var img = new Image();
    img.src = url;
    var dfd = $.Deferred();
    var size;

    if (img.complete) {
        var task = function () {
            size = crossBrowerSize(img);
            return dfd.resolve(size);
        };
        setTimeout(task, 5);
    } else {
        $(img).load(function () {
            size = crossBrowerSize(img);
            return dfd.resolve(size);
        });
    }
    $(img).error(function () {
        //toastr.error("找不到该图");
    });
    return dfd.promise();
}
function crossBrowerSize(img) {
    if ('naturalWidth' in (new Image)) {
        return { width: img.naturalWidth, height: img.naturalHeight };
    } else {
        return { width: img.width, height: img.height };
    }
}

var currentEdit;
function markerDialog(markerData) {
    var $dialog = $("#markerDialog");
    if (!markerData.accessTos) {
        var areaId = $("#parkAreaId").val();
        var field = { areaId: areaId, locationId: markerData.id || 0 };
        http.get("/MarkCoordinates/GetParkLocations", field).then(function (result) {
            var data = $.extend(markerData, { accessTos: result });
            kendo.bind($dialog, data);
            currentEdit = data;
        });
    } else {
        kendo.bind($dialog, markerData);
    }
    $dialog.data("kendoWindow").center().open();
}
function setSelectAttr(element) {
    $("#svg").children(":first-child").children("[data-select][data-type='path']").attr("data-select", "disselect");
    $("#marker").children("[data-marker]").attr("data-select", "disselect");
    $(element).attr("data-select", "select");
}
function marker(data) {
    $('<span class="k-marker k-marker-pin-target" data-marker="true" style="position:absolute" />')
       .attr("id", data.markerId || new Date().getTime())
       .css({ left: data.position && data.position.left, top: data.position && data.position.top })
       .dblclick(function () { markerDialog(data); })
       .click(function () { setSelectAttr($(this)); })
       .kendoDraggable({ hint: function (element) { return element.clone(); } })
       .kendoTooltip({ position: "top", content: function (e) { return $(e.target).data("marker").name; } })
       .appendTo("#marker")
       .data("marker", data);
}
function initMarker(data) {
    if (data.markers) {
        if (!(data.markers instanceof kendo.data.ObservableArray)) {
            data.markers = new kendo.data.ObservableArray(data.markers);
        }
        $.map(data.markers, marker);
    } else {
        data.markers = new kendo.data.ObservableArray([]);
    }
    $("#marker").data("markers", data.markers);
    $(document).keyup(function (e) {
        if (e.keyCode == 46) {
            var element = $("#marker").children("[data-marker][data-select='select']");
            if (element && element.length > 0) {
                $(element).data("kendoTooltip").hide();
                var elementData = $(element).data("marker");
                if (elementData) {
                    var markers = $("#marker").data("markers");
                    if (markers) {
                        $.each(markers, function (index, item) {
                            if (item && item.id == elementData.id) {
                                markers.splice(index, 1);
                            }
                        });
                    }
                }
                $(element).remove();
            }
            e.preventDefault();
        }
    });
}
function toUpperCase(str) {
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}
function toLowerCase(str) {
    return str.substring(0, 1).toLowerCase() + str.substring(1);
}
function toString(data, callback) {
    switch ($.type(data)) {
        case "string":
            return "\"" + data + "\"";
        case "array":
            var mapped = $.map(data, function (item) { return toString(item, callback); });
            return "[" + mapped.join(",") + "]";
        case "object":
            var str = [];
            $.each(data, function (key, val) {
                str.push(callback(key) + ':' + toString(val, callback));
            });
            return '{' + str.join(",") + '}';
        case 'number':
        case 'boolean':
            return data;
        case 'undefined':
        case 'null':
            return 'null';
        default:
            return data;
    }
}
function toObject(jsonData, callback) {
    var datStr = toString(jsonData, callback);
    return eval("(" + datStr + ")");
}
$(function () {
    var json;
    var id = $("#parkAreaId").val();
    initTool();
    http.post("/MarkCoordinates/Coordinates/" + id).then(function (result) {
        json = toObject(result, toLowerCase);
        createEditPaper(json);
        initMarker(json);
    });
    $("#markerDialog").kendoWindow({
        actions: ["Close"],
        draggable: true,
        pinned: true,
        height: "450px",
        modal: true,
        resizable: true,
        title: "编辑",
        width: "700px",
        visible: false,
        close: function () {
            kendo.unbind($("#markerDialog"));
        }
    });

    $("#selAccessTo").kendoMultiSelect({
        valuePrimitive: true,
        placeholder: "请选择...",
        dataTextField: "Name",
        dataValueField: "Id"
    });

    $("#markerSave").click(function () {
        $("#markerDialog").data("kendoWindow").close();
        http.post("/MarkCoordinates/SaveMarker?parkingAreaId=" + $("#parkAreaId").val(), currentEdit).then(function () {

        });
    });
    $("#markerCancel").click(function () {
        $("#markerDialog").data("kendoWindow").close();
    });
    $("#save").click(function () {
        if (json.shapes) {
            for (var i = 0; i < json.shapes.length; i++) {
                var item = json.shapes[i];
                if (!item || !(item.points) || item.points.length === 0) {
                    json.shapes.splice(i, 1);
                    i--;
                }
            }
        }
        var postData = $.extend({}, json);
        if (json.shapes) {
            postData.shapes = json.shapes.toJSON();
        }
        if (json.markers) {
            postData.markers = json.markers.toJSON();
        }
        postData = toObject(postData, toUpperCase);
        http.post("/MarkCoordinates/EditCoordinate", postData).then(function () {
            alert("保存成功");
        });
    });
});